package com.bj.disc.ui.splash.vm

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.ai3d.rfid.BuildConfig
import com.ai3d.rfid.base.vm.BaseViewModel
import com.ai3d.rfid.common.log.Logcat
import com.ai3d.rfid.common.proxy.MMKVProxy
import com.ai3d.rfid.common.proxy.MMKVProxy.KEY_DOWNLOAD_FILE_FINISH_LENGTH
import com.ai3d.rfid.common.proxy.MMKVProxy.KEY_NEED_DOWNLOAD
import com.ai3d.rfid.common.proxy.MMKVProxy.KEY_STATIC_ZIP_FILE_LENGTH
import com.ai3d.rfid.network.download.IDownloadListener
import com.ai3d.rfid.network.proxy.NetworkProxy
import com.bj.disc.util.DiscConstants.DOWNLOAD_FILE_STATIC_DIR
import com.bj.disc.util.DiscConstants.DOWNLOAD_FILE_STATIC_FILE_PATH
import com.bj.disc.util.DiscConstants.RESOURCE_ZIP_URL
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.ResponseBody
import retrofit2.Call
import java.io.File
import java.util.LinkedList

internal sealed class LauncherViewStatus
internal object PrivacyAgreementViewStatus : LauncherViewStatus() //隐私弹窗状态
internal object StaticZipDownloadState : LauncherViewStatus()              //判断是否需要下载static.zip
internal object StaticZipUnZipStatus : LauncherViewStatus()  //文件解压
internal object JudgeViewState : LauncherViewStatus()              //判断显示页面

/**
 * @ProjectName : Kolb
 * @Author : weijinsong
 * @Time : 2023/1/4 17:58
 * @Description : 启动页
 */
class SplashViewModel : BaseViewModel() {
    private val TAG = "SplashViewModel"
    private val mStepLinkedList = LinkedList<LauncherViewStatus>()
    internal val viewStatusMLD = MutableLiveData<LauncherViewStatus>()
    internal val retry = MutableLiveData<Boolean>()
    var call: Call<ResponseBody>? = null

    fun initStepList() {
        if (checkPrivacy()) {
            mStepLinkedList.add(PrivacyAgreementViewStatus)
        }

        if (MMKVProxy.getBoolean(KEY_NEED_DOWNLOAD, true)) {
            mStepLinkedList.add(StaticZipDownloadState)
            mStepLinkedList.add(StaticZipUnZipStatus)
        }

        mStepLinkedList.add(JudgeViewState)
    }

    /**
     * 拿出一个任务去执行
     */
    fun doNextStep() {
        Logcat.d(TAG, "doNextStep")
        if (mStepLinkedList.isEmpty()) return
        viewStatusMLD.postValue(mStepLinkedList.pop())
    }

    /**
     * 检查是否显示隐私弹窗
     */
    fun checkPrivacy(): Boolean {
        return BuildConfig.SHOW_POPUP_PRIVACY_AGREEMENT && MMKVProxy.getBoolean(
            MMKVProxy.KEY_PRIVACY_AGREE,
            true
        )
    }

    fun userInfo(token: String?) {
        if (token == null)
            return

    }

    fun downloadStaticFile(iDownloadListener: IDownloadListener) {
        Logcat.d(TAG, "downloadStaticFile")
        var isNeedRange = MMKVProxy.getBoolean(MMKVProxy.KEY_NEED_DOWNLOAD_RANGE, false)//是否需要定点续传
        viewModelScope.launch(Dispatchers.IO) {
            runCatching {
                var range = "bytes=0-"
                //定点续传
                var dirFile = File(DOWNLOAD_FILE_STATIC_DIR)
                if (!dirFile.exists()) {
                    dirFile.mkdir()
                }
                var resourceZipFile = File(DOWNLOAD_FILE_STATIC_FILE_PATH)
                Logcat.d(
                    TAG,
                    "downloadStaticFile !resourceZipFile.exists() : ${!resourceZipFile.exists()}"
                )

                if (!resourceZipFile.exists()) {
                    MMKVProxy.setLong(KEY_STATIC_ZIP_FILE_LENGTH, 0)//防止文件被删除
                    resourceZipFile.createNewFile()
                    Logcat.d(
                        TAG,
                        "downloadStaticFile resourceZipFile.createNewFile() : ${resourceZipFile.createNewFile()}"
                    )
                }

                if (isNeedRange) {//需要定点续传
                    range = "bytes=${resourceZipFile.length()}-"
                }
                MMKVProxy.setLong(KEY_DOWNLOAD_FILE_FINISH_LENGTH, resourceZipFile.length())
                Logcat.d(
                    TAG,
                    "downloadStaticFile 1 isNeedRange : $isNeedRange range : $range file length : ${resourceZipFile.length()}"
                )

                Logcat.d(TAG, "downloadStaticFile 1 isNeedRange : $isNeedRange range : $range")
                // 调用 Retrofit 接口方法下载文件
                call = NetworkProxy.createDownFileRetrofit(iDownloadListener)
                    .downloadFile(RESOURCE_ZIP_URL, range)
                // 获取 ResponseBody 并进行文件写入
                val response: ResponseBody? = call?.execute()?.body()
                response
            }.onSuccess {
                try {
                    Logcat.d(
                        TAG,
                        "downloadStaticFile it?.contentLength() : ${it?.contentLength()} ${it?.contentLength() == null} ${
                            MMKVProxy.getLong(KEY_STATIC_ZIP_FILE_LENGTH)
                        }  isNeedRange : $isNeedRange"
                    )
                    var isSameFile =
                        it?.contentLength() == null || MMKVProxy.getLong(KEY_STATIC_ZIP_FILE_LENGTH) == it?.contentLength()//内容为空代表定点传送已完成
                    if (!isNeedRange) {//非续传时，记住文件大小
                        MMKVProxy.setLong(KEY_STATIC_ZIP_FILE_LENGTH, it?.contentLength()!!)
                    }
                    if (!isSameFile || isNeedRange) {//不是同个文件，需要重新下载 或者 是同个文件，单是需要续写
                        it?.byteStream()?.let { it1 ->
                            Logcat.d(TAG, "downloadStaticFile 文件写入 ")
                            MMKVProxy.setBoolean(MMKVProxy.KEY_NEED_DOWNLOAD_RANGE, true)//状态改为定点续传
                            it?.contentLength()?.let { it2 ->

                            }
                        }
                    } else {
                        it?.close()
                        doNextStep()
                    }
                }catch (e:Exception){
                    it?.close()
                    iDownloadListener.onFail("")
                    e.printStackTrace()
                }
            }.onFailure {
                //doNextStep()
                iDownloadListener.onFail("")
            }
        }

    }



    private var firstResume = true
    fun onPause() {
        firstResume = false
        call?.cancel()

    }

    fun onResume() {
        if (!firstResume && !checkPrivacy() && !MMKVProxy.getBoolean(
                MMKVProxy.KEY_NEED_NEED_UNZIP,
                false
            )//文件需要解压，则说明下载过，无需下载
        ) {
            Logcat.d(TAG, "onResume")
            mStepLinkedList.clear()
            mStepLinkedList.add(StaticZipDownloadState)
            mStepLinkedList.add(StaticZipUnZipStatus)
            mStepLinkedList.add(JudgeViewState)
            doNextStep()
        }
    }
}